package com.yp.infrastructure.common.annotation.callback;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseFieldCallback implements ReflectionUtils.FieldCallback {


    abstract Class<? extends Annotation> getAnnotationClass();

    private static Map<String, Integer> map = new HashMap<>();

    public static Map<String, Integer> getMap() {
        return map;
    }

    public static void setMap(Map<String, Integer> map) {
        BaseFieldCallback.map = map;
    }

    public ConfigurableListableBeanFactory getConfigurableBeanFactory() {
        return configurableBeanFactory;
    }

    public void setConfigurableBeanFactory(ConfigurableListableBeanFactory configurableBeanFactory) {
        this.configurableBeanFactory = configurableBeanFactory;
    }

    public Object getBean() {
        return bean;
    }

    public void setBean(Object bean) {
        this.bean = bean;
    }

    private ConfigurableListableBeanFactory configurableBeanFactory;
    private Object bean;

    BaseFieldCallback(ConfigurableListableBeanFactory bf, Object bean) {
        configurableBeanFactory = bf;
        this.bean = bean;
    }

    public void doWith(Field field) throws IllegalArgumentException {
        if (!field.isAnnotationPresent(getAnnotationClass())) {
            return;
        }
        int count = 1;
        String beanName = field.getName();
        if (map.containsKey(beanName)) {
            count = map.get(beanName) + 1;
        }
        map.put(beanName, count);
    }
}
